package com.jrx.anytxn.param.controller.product;

import com.google.common.collect.Maps;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.dto.product.ProductTableReq;
import com.jrx.anytxn.param.dto.product.ProductTableRes;
import com.jrx.anytxn.param.plugins.DeleteLog;
import com.jrx.anytxn.param.plugins.DeleteLogHelper;
import com.jrx.anytxn.param.service.product.IProductTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jrx.auth.filter.service.InfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * 产品表
 *
 * @author 黄秋平
 * @date 2020-5-26 15:31:28
 */
@Api(tags = "页面产品参数API接口")
@RestController
@RequestMapping(value = "/param/products")
public class ProductTableController {

    private static final Logger logger = LoggerFactory.getLogger(ProductTableController.class);

    @Resource
    IProductTableService productTableService;

    @Resource
    private InfoService infoService;

    @ApiOperation(value = "根据租户ID和产品ID查询产品表信息", notes = "根据租户ID和产品ID查询产品表信息")
    @GetMapping(value = "/{tenantId}/{productId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true),
            @ApiImplicitParam(name = "productId", value = "产品ID", required = true)
    })
    public TxnRespResult<ProductTableRes> getByTenIdAndProId(@NotNull @PathVariable String tenantId, @PathVariable String productId) {
        TxnRespResult<ProductTableRes> result = new TxnRespResult<>();
        ProductTableRes res;
        try {
            res = productTableService.findByTenIdAndProId(String.valueOf(infoService.getUser().getProjectId()), productId);
            if (res.getClassify1Rate() != null && res.getClassify1Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                res.setClassify1Rate(res.getClassify1Rate().multiply(BigDecimal.valueOf(100)));
            }
            if (res.getClassify2Rate() != null && res.getClassify2Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                res.setClassify2Rate(res.getClassify2Rate().multiply(BigDecimal.valueOf(100)));
            }
            if (res.getClassify3Rate() != null && res.getClassify3Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                res.setClassify3Rate(res.getClassify3Rate().multiply(BigDecimal.valueOf(100)));
            }
            if (res.getClassify4Rate() != null && res.getClassify4Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                res.setClassify4Rate(res.getClassify4Rate().multiply(BigDecimal.valueOf(100)));
            }
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID分页查询产品表信息", notes = "根据租户ID分页查询产品表信息")
    @GetMapping(value = "/pageNum/{pageNum}/pageSize/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", required = true)})
    public TxnRespResult<TxnPage<ProductTableRes>> getAllPage(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {

        TxnRespResult<TxnPage<ProductTableRes>> result = new TxnRespResult<>();
        TxnPage<ProductTableRes> response;
        try {
            String tenantId=String.valueOf(infoService.getUser().getProjectId());
            response = productTableService.findAllPageByTenId(pageNum, pageSize, tenantId);
            result.getSuccess(response);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "新增产品表信息", notes = "新增产品表信息")
    @PostMapping("/")
    public TxnRespResult<ProductTableRes> createProductTable(@RequestBody ProductTableReq productTableReq) {
        ProductTableRes res;
        TxnRespResult<ProductTableRes> result = new TxnRespResult<>();
        try {
            productTableReq.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
            productTableReq.setUpdateBy(infoService.getUser().getUserName());
            productTableReq.setAllowTerms(" ");
            if (productTableReq.getClassify1Rate() != null && productTableReq.getClassify1Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                productTableReq.setClassify1Rate(productTableReq.getClassify1Rate().divide(BigDecimal.valueOf(100)));
            }
            if (productTableReq.getClassify2Rate() != null && productTableReq.getClassify2Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                productTableReq.setClassify2Rate(productTableReq.getClassify2Rate().divide(BigDecimal.valueOf(100)));
            }
            if (productTableReq.getClassify3Rate() != null && productTableReq.getClassify3Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                productTableReq.setClassify3Rate(productTableReq.getClassify3Rate().divide(BigDecimal.valueOf(100)));
            }
            if (productTableReq.getClassify4Rate() != null && productTableReq.getClassify4Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                productTableReq.setClassify4Rate(productTableReq.getClassify4Rate().divide(BigDecimal.valueOf(100)));
            }
            res = productTableService.addProductTable(productTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID编辑产品表信息", notes = "根据租户ID编辑产品表信息")
    @PutMapping("/")
    public TxnRespResult<ProductTableRes> modifyProductTable(@RequestBody ProductTableReq productTableReq) {
        TxnRespResult<ProductTableRes> result = new TxnRespResult<>();
        ProductTableRes res;
        try {
            productTableReq.setUpdateBy(infoService.getUser().getUserName());
            if (productTableReq.getClassify1Rate() != null && productTableReq.getClassify1Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                productTableReq.setClassify1Rate(productTableReq.getClassify1Rate().divide(BigDecimal.valueOf(100)));
            }
            if (productTableReq.getClassify2Rate() != null && productTableReq.getClassify2Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                productTableReq.setClassify2Rate(productTableReq.getClassify2Rate().divide(BigDecimal.valueOf(100)));
            }
            if (productTableReq.getClassify3Rate() != null && productTableReq.getClassify3Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                productTableReq.setClassify3Rate(productTableReq.getClassify3Rate().divide(BigDecimal.valueOf(100)));
            }
            if (productTableReq.getClassify4Rate() != null && productTableReq.getClassify4Rate().compareTo(BigDecimal.valueOf(0)) != 0) {
                productTableReq.setClassify4Rate(productTableReq.getClassify4Rate().divide(BigDecimal.valueOf(100)));
            }
            res = productTableService.modifyProductTable(productTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID和产品ID删除产品表信息", notes = "根据租户ID和产品ID删除产品表信息")
    @DeleteMapping(value = "/{tenantId}/{productId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true),
            @ApiImplicitParam(name = "productId", value = "产品ID", required = true)
    })
    public TxnRespResult<Boolean> removeByTenIdAndProId(@NotNull @PathVariable String tenantId, @PathVariable String productId) {
        TxnRespResult<Boolean> result = new TxnRespResult<>();
        Boolean flag;
        try {
            DeleteLog deleteLog = new DeleteLog(infoService.getUser().getUserName());
            DeleteLogHelper.setDelleteHistory(deleteLog);

            flag = productTableService.removeByTenIdAndProId(String.valueOf(infoService.getUser().getProjectId()), productId);
            result.getSuccess(flag);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        } finally {
            DeleteLogHelper.clearLocalHistory();
        }
        return result;
    }

    @ApiOperation(value = "获得产品表下拉信息", notes = "获得产品表下拉信息")
    @GetMapping(value = "/list")
    public TxnRespResult<HashMap<String, List<ProductTableRes>>> getAllProList() {
        TxnRespResult<HashMap<String, List<ProductTableRes>>> result = new TxnRespResult<>();
        String tenantId=String.valueOf(infoService.getUser().getProjectId());
        List<ProductTableRes> allProduct = productTableService.findAllProductByTenId(tenantId);
        HashMap<String, List<ProductTableRes>> sysCodeMap = Maps.newHashMap();
        sysCodeMap.put("listData", allProduct);
        return result.getSuccess(sysCodeMap);
    }

    @ApiOperation(value = "根据机构号获取有效产品列表信息", notes = "根据机构号获取有效产品列表信息")
    @GetMapping(value = "/list/orgId/{orgId}")
    @ApiImplicitParam(name = "orgId", value = "机构号", required = true)
    public TxnRespResult<HashMap<String, List<ProductTableRes>>> getProductTableByOrgId(@PathVariable(value = "orgId") String orgId) {
        logger.debug("get ProductTableByOrgId start");
        TxnRespResult<HashMap<String, List<ProductTableRes>>> result = new TxnRespResult<>();

        List<ProductTableRes> productTableResList;
        try {
            String tenantId=String.valueOf(infoService.getUser().getProjectId());
            productTableResList = productTableService.findProductByOrgIdAndTenId(orgId, tenantId);
            HashMap<String, List<ProductTableRes>> sysCodeMap = Maps.newHashMap();
            sysCodeMap.put("listData", productTableResList);
            result.getSuccess(sysCodeMap);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        logger.debug("get ProductTableByOrgId end");
        return result;
    }

}
